package com.shuyuansystem.controller;

import com.shuyuansystem.dao.OrderInfoMapper;
import com.shuyuansystem.dao.OrderListMapper;
import com.shuyuansystem.pojo.OrderInfo;
import com.shuyuansystem.pojo.OrderList;
import com.shuyuansystem.pojo.PaymentRequest;
import com.shuyuansystem.utils.OrderInfoUtils;
import com.shuyuansystem.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class OrderListController {

    @Autowired
    private OrderListMapper orderListMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/orderList")
    public PageResult<Map<String, Object>> getOrderList(
            @RequestParam String userId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "1") int pageSize) {

        // 从数据库获取商家 ID 列表
        Map<String, Map<String, Object>> result = orderListMapper.getMerchantIdListByUserId(userId);

        // 存储所有商家的订单信息
        List<Map<String, Object>> allMerchantOrders = new ArrayList<>();

        for (Map.Entry<String, Map<String, Object>> entry : result.entrySet()) {
            String userID = entry.getKey();
            Map<String, Object> row = entry.getValue();
            String merchantIdList = (String) row.get("merchant_id_list");

            // 将 merchantIdList 转换为 List<String>
            List<String> merchantIds = new ArrayList<>();
            if (merchantIdList != null &&!merchantIdList.isEmpty()) {
                String[] ids = merchantIdList.split(",");
                Collections.addAll(merchantIds, ids);
            }

            // 根据 userId 和 merchantIds 查询订单列表
            List<OrderList> orderList = orderListMapper.getOrdersByUserIdAndMerchantIds(userId, merchantIds);

            // 按 merchant_id 分组
            Map<String, List<OrderList>> merchantIdToOrdersMap = new HashMap<>();
            // 存储每个商家的总价
            Map<String, Double> merchantTotalPriceMap = new HashMap<>();

            for (OrderList order : orderList) {
                String merchantId = order.getMerchant_id();
                merchantIdToOrdersMap.computeIfAbsent(merchantId, k -> new ArrayList<>()).add(order);
                // 累加每个商家的总价
                merchantTotalPriceMap.put(merchantId, merchantTotalPriceMap.getOrDefault(merchantId, 0.0) + order.getTotal_price());
            }

            // 处理每个商家的订单信息
            for (Map.Entry<String, List<OrderList>> merchantEntry : merchantIdToOrdersMap.entrySet()) {
                String merchantId = merchantEntry.getKey();
                List<OrderList> merchantOrders = merchantEntry.getValue();
                double totalPrice = merchantTotalPriceMap.get(merchantId);

                Map<String, Object> merchantInfo = new HashMap<>();
                merchantInfo.put("merchantId", merchantId);
                merchantInfo.put("totalPrice", totalPrice);
                merchantInfo.put("orders", merchantOrders);

                allMerchantOrders.add(merchantInfo);
            }
        }

        // 进行分页处理
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allMerchantOrders.size());
        List<Map<String, Object>> currentPageOrders = allMerchantOrders.subList(startIndex, endIndex);

        // 封装分页结果
        return new PageResult<>((long) allMerchantOrders.size(), currentPageOrders);
    }

    @PostMapping("/submitOrder")
    public Map<String, Object> submitOrder(@RequestBody Map<String, Object> data) {
        Map<String, Object> response = new HashMap<>();
        try {
            String userId = (String) data.get("userId");
            List<Map<String, Object>> merchantInfos = (List<Map<String, Object>>) data.get("merchantInfos");
            String totalPrice = (String) data.get("totalPrice");
            String shippingAddress = (String) data.get("shippingAddress");
            String receiverPhone = (String) data.get("receiverPhone");
            String receiverName = (String) data.get("receiverName");
            String remark = (String) data.get("remark");
            String transactionStatus = (String) data.get("transactionStatus");
            String orderStatus = (String) data.get("orderStatus");

            Map<String, String> orderNumbers = new HashMap<>();

            // 清空 Redis 中该用户的相关订单号数据
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            for (Map<String, Object> merchantInfo : merchantInfos) {
                String merchantId = (String) merchantInfo.get("merchantId");
                String redisKey = userId + ":" + merchantId;
                redisTemplate.delete(redisKey);
            }

            for (Map<String, Object> merchantInfo : merchantInfos) {
                String merchantId = (String) merchantInfo.get("merchantId");
                String merchantTotalPrice = merchantInfo.get("totalPrice").toString();
                BigDecimal totalPriceBD = BigDecimal.valueOf(Double.parseDouble(merchantTotalPrice));

                // 检查是否存在相同 userId、merchantId、总价格且订单状态为未支付的订单
                List<OrderInfo> duplicateUnpaidOrders = orderInfoMapper.checkDuplicateUnpaidOrder(userId, merchantId, totalPriceBD, "订单未支付");
                if (!duplicateUnpaidOrders.isEmpty()) {
                    // 存在重复未支付订单，不进行插入操作，直接返回 null
                    return null;
                }

                // 生成唯一的订单号
                String merchantOrderNumber = UUID.randomUUID().toString();

                OrderInfo orderInfo = new OrderInfo();
                orderInfo.setUserId(userId);
                orderInfo.setMerchantId(merchantId);
                orderInfo.setReceiverName(receiverName);
                orderInfo.setTotalPrice(totalPriceBD);
                orderInfo.setShippingAddress(shippingAddress);
                orderInfo.setReceiverPhone(receiverPhone);
                orderInfo.setRemark(remark);
                orderInfo.setMerchantOrderNumber(merchantOrderNumber);
                orderInfo.setTransactionStatus(transactionStatus);
                orderInfo.setOrderStatus(orderStatus);

                // 插入订单信息到数据库
                orderInfoMapper.insertOrderInfo(orderInfo);

                orderNumbers.put(merchantId, merchantOrderNumber);

                // 将订单号存储到 Redis 中
                String redisKey = userId + ":" + merchantId;
                ops.set(redisKey, merchantOrderNumber, 1, TimeUnit.DAYS);

                // 更新 order_list 表中的 merchant_order_number 列
                orderListMapper.updateMerchantOrderNumber(userId, merchantId, merchantOrderNumber);
            }

            response.put("success", true);
            response.put("orderNumbers", orderNumbers);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "提交订单失败: " + e.getMessage());
        }
        return response;
    }

    @RequestMapping("pay")
    @ResponseBody
    public Map<String, String> pay(@RequestParam String userId, @RequestParam int pageNum, @RequestParam int pageSize) {
        // 打印获取到的 userId
        System.out.println("获取到的 userId: " + userId);

        Map<String, String> orderNumbers = new HashMap<>();
        // 从数据库获取商家 ID 列表
        Map<String, Map<String, Object>> result = orderListMapper.getMerchantIdListByUserId(userId);

        // 存储所有商家的订单信息
        List<Map<String, Object>> allMerchantOrders = new ArrayList<>();

        for (Map.Entry<String, Map<String, Object>> entry : result.entrySet()) {
            String userID = entry.getKey();
            Map<String, Object> row = entry.getValue();
            String merchantIdList = (String) row.get("merchant_id_list");

            // 将 merchantIdList 转换为 List<String>
            List<String> merchantIds = new ArrayList<>();
            if (merchantIdList != null &&!merchantIdList.isEmpty()) {
                String[] ids = merchantIdList.split(",");
                Collections.addAll(merchantIds, ids);
            }

            // 根据 userId 和 merchantIds 查询订单列表
            List<OrderList> orderList = orderListMapper.getOrdersByUserIdAndMerchantIds(userId, merchantIds);

            // 按 merchant_id 分组
            Map<String, List<OrderList>> merchantIdToOrdersMap = new HashMap<>();
            // 存储每个商家的总价
            Map<String, Double> merchantTotalPriceMap = new HashMap<>();

            for (OrderList order : orderList) {
                String merchantId = order.getMerchant_id();
                merchantIdToOrdersMap.computeIfAbsent(merchantId, k -> new ArrayList<>()).add(order);
                // 累加每个商家的总价
                merchantTotalPriceMap.put(merchantId, merchantTotalPriceMap.getOrDefault(merchantId, 0.0) + order.getTotal_price());
            }

            // 处理每个商家的订单信息
            for (Map.Entry<String, List<OrderList>> merchantEntry : merchantIdToOrdersMap.entrySet()) {
                String merchantId = merchantEntry.getKey();
                List<OrderList> merchantOrders = merchantEntry.getValue();
                double totalPrice = merchantTotalPriceMap.get(merchantId);

                Map<String, Object> merchantInfo = new HashMap<>();
                merchantInfo.put("merchantId", merchantId);
                merchantInfo.put("totalPrice", totalPrice);
                merchantInfo.put("orders", merchantOrders);

                allMerchantOrders.add(merchantInfo);
            }
        }

        // 进行分页处理
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, allMerchantOrders.size());
        List<Map<String, Object>> currentPageOrders = allMerchantOrders.subList(startIndex, endIndex);

        // 从 Redis 中获取订单号
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        for (Map<String, Object> merchantInfo : currentPageOrders) {
            String merchantId = (String) merchantInfo.get("merchantId");
            String redisKey = userId + ":" + merchantId;
            String orderNumber = ops.get(redisKey);
            if (orderNumber != null) {
                orderNumbers.put(merchantId, orderNumber);
            }
        }
        // 打印获取到的 orderNumbers
        System.out.println("获取到的 orderNumbers: " + orderNumbers);
        System.out.println("userID: " + userId);

        // 将 orderNumbers 和 userId 写入 Redis
        String redisKey = "payment_info:" + userId;
        String orderNumbersStr = orderNumbers.toString();
        ops.set(redisKey, orderNumbersStr);

        return orderNumbers;
    }

    @PostMapping("payforAli")
    public String payforAli(@RequestParam String userId) {
        // 从 Redis 中获取订单信息
        String redisKey = "payment_info:" + userId;
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String orderNumbersStr = ops.get(redisKey);

        if (orderNumbersStr != null) {
            // 打印获取到的信息
            System.out.println("从 Redis 获取的信息 - 用户 ID: " + userId);
            System.out.println("从 Redis 获取的信息 - 订单号信息: " + orderNumbersStr);

            // 将字符串转换为 Map
            Map<String, String> orderNumbers = parseOrderNumbers(orderNumbersStr);

            // 打印解析后的商家 ID 和订单号信息
            for (Map.Entry<String, String> entry : orderNumbers.entrySet()) {
                String merchantId = entry.getKey();
                String orderNumber = entry.getValue();
                System.out.println("商家 ID: " + merchantId + ", 订单号: " + orderNumber);
            }


        }

        // 在这里添加具体的支付逻辑
        return "支付请求已接收";
    }

    private Map<String, String> parseOrderNumbers(String orderNumbersStr) {
        Map<String, String> orderNumbers = new HashMap<>();
        // 去除首尾的大括号
        String trimmedStr = orderNumbersStr.substring(1, orderNumbersStr.length() - 1);
        String[] pairs = trimmedStr.split(", ");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            if (keyValue.length == 2) {
                orderNumbers.put(keyValue[0], keyValue[1]);
            }
        }
        return orderNumbers;
    }
}